package file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * This class saves Strings in a file and load from a file to Strings.
 * 
 * @author Richard Pula
 *
 */
public class PersistenceFile {
	
	public static final String LINE_SEPARATOR = System.getProperty("line.separator");	
	public static final String SPACE 		  = " ";
	
	/**
	 * Saves a String to a file.
	 * 
	 * @param file The file's destination path.
	 * @param toWrite The string to save into the file.
	 */
	static public void stringToFile(String file, String toWrite) {
		try {
			FileWriter writer = new FileWriter(file);
			writer.write(toWrite);
			writer.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * Load a file into a String.
	 * 
	 * @param file The file which will be load the String
	 * @return A String with the file content.
	 */
	static public String fileToString(String file) {
		StringBuffer sb = new StringBuffer();
		
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String input;
			
			while (((input = reader.readLine()) != null)) {
				sb.append(input);
				sb.append(PersistenceFile.LINE_SEPARATOR);
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}		
		
		return sb.toString();
	}
	 
}
